package org.i1510.wx.utils.Token;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.i1510.common.utils.KBProperties;
import org.i1510.wx.utils.WxUtils;


public class TokenUtils {
	/**
	 * 每个公众号的token对象 键值对
	 */
	public static Map<String, Map<String, Object>> tokenMap = new HashMap<String, Map<String, Object>>();
	
	/**
	*@Author Rambo
	*@Desc：获取tokeId(同步锁)
	*@param wxPublicId 公众号唯一ID
	*@param appId 
	*@param appSecret
	*@return TODO
	*@Version  TokenUtils.java,v 1.1 2014-10-10 上午10:43:05 
	*/
	public synchronized static String checkTokenGZH(String wxPublicId, String appId,
			String appSecret) {
		
		String key = wxPublicId;
		Map<String, Object> map = tokenMap.get(key);
		
		String tokenId = "";
		if (map == null) {
			map = new HashMap<String, Object>();
			Long beginTime = new Date().getTime();
			AccessToken accessToken = WxUtils.getAccessToken4GZH(appId,
					appSecret);
			tokenId = accessToken.getToken();
			map.put("tokenKey", accessToken);
			map.put("beginTime", beginTime);
			tokenMap.put(key, map);

		} else {

			AccessToken accessToken = (AccessToken) map.get("tokenKey");
			// 获取该token的时间(ms)
			Long beginTime = (Long) map.get("beginTime");

			// 获取现在时间(ms)
			Long nowTime = new Date().getTime();

			// 从获取该token时的时间到现在总共过去了多少秒(ms)
			Long timeLag = nowTime - beginTime;

			// 该token最长有效时间(s)
			int expiresTime = accessToken.getExpiresIn();

			
			boolean flag = (timeLag / 1000 - KBProperties.WX_TOKEN_DELAY) > expiresTime;

			// 表示该token已经失效，需要再次获取新的token
			if (flag) {
				Long beginNewTime = new Date().getTime();
				accessToken = WxUtils.getAccessToken4GZH(appId, appSecret);
				map.put("tokenKey", accessToken);
				map.put("beginTime", beginNewTime);
			}
			tokenId = accessToken.getToken();
		}
		return tokenId;
	}
}
